package com.junlong0716.enjoylearning.service

import android.app.Service
import android.content.Intent
import android.content.ServiceConnection
import android.media.MediaPlayer
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.constant.NetConstant.REQUEST_SOURCE
import com.junlong0716.enjoylearning.entity.RememberPlayMusicEntity
import com.junlong0716.enjoylearning.entity.rxevent.MusicPlayDurationEvent
import com.junlong0716.enjoylearning.entity.rxevent.MusicPlayStateEvent
import com.junlong0716.module.common.constant.Constant
import com.junlong0716.module.common.rxbus.RxBus
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.realm.Realm
import java.util.concurrent.TimeUnit

/**
 *@author: EdsionLi
 *@description:
 *@date: Created in 2018/5/30 下午4:39
 *@modified by:
 */
class OldMusicService : Service() {

    inner class MyBinder : Binder() {
        fun getService(): OldMusicService {
            return this@OldMusicService
        }
    }

    private var mediaPlayer: MediaPlayer? = null
    private var myBinder: MyBinder = MyBinder()
    private var setOnMediaStateListener: SetOnMediaStateListener? = null
    private var disposable: Disposable? = null
    private var musicName = ""
    private var musicAvatar = ""
    private var musicId = 0
    private var musicPath = ""
    private lateinit var realm: Realm
    private var rememberPlayMusic: RememberPlayMusicEntity? = null
    private var currentDuring: Int = 0
    private lateinit var commentPresenter: CommentPresenter
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: MusicPlayStateEvent) {
        if (s.eventKey == 0x9898) {
            if (s.onPause) {
                pausePlay()
            } else {
                startPlay()
            }
        }
    }

    override fun onBind(intent: Intent?): IBinder {
        return myBinder
    }


    override fun onCreate() {
        super.onCreate()

        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this)
        }

        realm = Realm.getDefaultInstance()

        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer()
        }

        mediaPlayer!!.setOnPreparedListener { mp ->
            mp!!.start()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        musicPath = intent!!.getStringExtra("MUSIC_PATH")
        musicName = intent.getStringExtra("MUSIC_NAME")
        musicAvatar = intent.getStringExtra("MUSIC_AVATAR")
        musicId = intent.getIntExtra("MUSIC_ID", 0)

        commentPresenter = CommentPresenter()
        commentPresenter.requestAddStudyTime(this, musicId, object : CommentPresenter.AddStudyTimeCallback {
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })

        mediaPlayer!!.reset()
        mediaPlayer!!.setDataSource(REQUEST_SOURCE + musicPath)
        mediaPlayer!!.prepareAsync()

        //是否循环播放
        mediaPlayer!!.isLooping = false

        rememberPlayMusic = realm.where(RememberPlayMusicEntity::class.java).equalTo("musicId", musicId).findFirst()

        mediaPlayer!!.setOnCompletionListener {
            //            mediaPlayer!!.reset()
            //RxBus.getDefault().post(MusicPlayStateEvent(0x9898,true))
            //           RxBus.getDefault().post(MusicPlayStateEvent(0x9898,true))
            //RxBus.getDefault().post(MusicPlayComplete(0x9899))
            //stopSelf()
            //setOnMediaStateListener!!.onComplete()
//            ToastUtils.showShort("播放完成！")


            //播放完成 将数据从数据库中删掉
//            val rememberPlayMusicEntity = realm.where(RememberPlayMusicEntity::class.java).equalTo("musicId", musicId).findFirst()
//
//            realm.executeTransaction { it ->
//                rememberPlayMusicEntity?.deleteFromRealm()
//            }

            //ToastUtils.showShort("播放完成")

            val intent = Intent(this, RecordStudyEndService::class.java)
            intent.putExtra("KNOWLEDGE_ID", musicId)
            startService(intent)
            RxBus.getDefault().post(MusicPlayStateEvent(0x9898, true))
        }


        //先查询是否有该条数据 没有则新增
        if (rememberPlayMusic == null) {
            realm.executeTransaction { it ->
                val rememberPlayMusicEntity = RememberPlayMusicEntity()
                rememberPlayMusicEntity.musicId = musicId
                rememberPlayMusicEntity.currentDuring = 0
                it.copyToRealm(rememberPlayMusicEntity)
            }
        } else {
            //有的话 直接从记录的位置进行播放
            currentDuring = rememberPlayMusic!!.currentDuring!!
        }

        mediaPlayer!!.setOnPreparedListener {
            mediaPlayer!!.start()
            mediaPlayer!!.seekTo(currentDuring)
        }

        if (disposable != null && !disposable!!.isDisposed) {
            disposable!!.dispose()
        }

        disposable = Observable.interval(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { it ->
                    RxBus.getDefault().post(MusicPlayDurationEvent(Constant.MUSIC_DURATION_VALUE, getCurrentPosition() + 1))
                }

        return START_NOT_STICKY
    }

    fun startPlay() {
        mediaPlayer!!.start()
        commentPresenter = CommentPresenter()
        commentPresenter.requestAddStudyTime(this, musicId, object : CommentPresenter.AddStudyTimeCallback {
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })

    }

    fun pausePlay() {
        val intent = Intent(this, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID", musicId)
        startService(intent)
    }

    fun getPlayerState(): Boolean {
        return mediaPlayer!!.isPlaying
    }

    fun getDuration(): Int {
        return mediaPlayer!!.duration
    }

    fun getCurrentPosition(): Int {
        return mediaPlayer!!.currentPosition
    }

    fun setSeekToPosition(position: Int) {
        mediaPlayer!!.seekTo(position)
    }

    interface SetOnMediaStateListener {
        fun onComplete()
    }

    fun setOnMediaStateListener(setOnMediaStateListener: SetOnMediaStateListener) {
        this.setOnMediaStateListener = setOnMediaStateListener
    }

    override fun unbindService(conn: ServiceConnection?) {
        super.unbindService(conn)
    }

    fun getMusicName(): String {
        return musicName
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!disposable!!.isDisposed) {
            disposable!!.dispose()
        }

        val intent = Intent(this, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID", musicId)
        startService(intent)

        realm.executeTransaction { it ->
            val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", musicId).findFirst()
            if (rememberPlayMusicEntity != null) {
                rememberPlayMusicEntity.currentDuring = mediaPlayer!!.currentPosition
            }
        }

        realm.close()

        mediaPlayer!!.stop()
        mediaPlayer!!.reset()
        mediaPlayer!!.release()
        mediaPlayer = null

        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }
    }

    fun getMusicAvatar(): String {
        return musicAvatar
    }

    fun getMusicId(): Int {
        return musicId
    }

    fun getMusicUrl(): String {
        return REQUEST_SOURCE + musicPath
    }


    fun nextMusic(id: Int, fileAddress: String, knowledgeTitle: String, coverImg: String) {

        realm.executeTransaction { it ->
            val rememberPlayMusicEntity = it.where(RememberPlayMusicEntity::class.java).equalTo("musicId", musicId).findFirst()
            if (rememberPlayMusicEntity != null) {
                rememberPlayMusicEntity.currentDuring = mediaPlayer!!.currentPosition
            }
        }

        musicPath = fileAddress
        musicName = knowledgeTitle
        musicAvatar = coverImg
        musicId = id

        rememberPlayMusic = realm.where(RememberPlayMusicEntity::class.java).equalTo("musicId", musicId).findFirst()

        mediaPlayer!!.pause()
        mediaPlayer!!.reset()
        mediaPlayer!!.setDataSource(NetConstant.REQUEST_SOURCE + musicPath)
        mediaPlayer!!.prepareAsync()


        //先查询是否有该条数据 没有则新增
        if (rememberPlayMusic == null) {
            realm.executeTransaction { it ->
                val rememberPlayMusicEntity = RememberPlayMusicEntity()
                rememberPlayMusicEntity.musicId = musicId
                rememberPlayMusicEntity.currentDuring = 0
                it.copyToRealm(rememberPlayMusicEntity)
            }
        } else {
            //有的话 直接从记录的位置进行播放
            currentDuring = rememberPlayMusic!!.currentDuring!!
        }

        mediaPlayer!!.setOnPreparedListener {
            mediaPlayer!!.start()
            mediaPlayer!!.seekTo(currentDuring)
        }
    }
}